<template>
  <el-container class="layout-container">
    <el-header class="layout-header">
      <div class="header-content">
        <div class="header-left">
          <div class="logo">
            <svg width="32" height="32" viewBox="0 0 64 64" fill="none">
              <rect width="64" height="64" rx="8" fill="#409eff"/>
              <path d="M32 20L24 28H28V40H36V28H40L32 20Z" fill="white"/>
            </svg>
          </div>
          <h1 class="header-title">员工事务管理系统</h1>
        </div>
        <div class="header-right">
          <!-- 消息中心入口 -->
          <el-badge 
            :value="unreadCount" 
            :hidden="unreadCount === 0"
            class="notification-badge"
          >
            <el-button 
              circle 
              @click="goToNotification"
              class="notification-btn"
            >
              <el-icon><Bell /></el-icon>
            </el-button>
          </el-badge>
          
          <el-dropdown @command="handleCommand" trigger="click">
            <div class="user-dropdown">
              <el-avatar :size="36" :src="userAvatar">
                <span>{{ userInfo.name ? userInfo.name.charAt(0) : 'U' }}</span>
              </el-avatar>
              <div class="user-info-text">
                <span class="user-name">{{ userInfo.name || '用户' }}</span>
                <span class="user-role">{{ getRoleName(userInfo.role) }}</span>
              </div>
              <el-icon class="dropdown-icon"><ArrowDown /></el-icon>
            </div>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="profile">
                  <el-icon><User /></el-icon>
                  <span style="margin-left: 8px">个人信息</span>
                </el-dropdown-item>
                <el-dropdown-item divided command="logout">
                  <el-icon><SwitchButton /></el-icon>
                  <span style="margin-left: 8px">退出登录</span>
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </div>
    </el-header>
    <el-container class="layout-body">
      <el-aside class="layout-aside" width="240px">
        <el-menu
          :default-active="activeMenu"
          router
          class="sidebar-menu"
          :collapse="false"
        >
          <el-menu-item 
            v-for="item in menuList" 
            :key="item.path" 
            :index="item.path"
            class="menu-item"
          >
            <el-icon v-if="getMenuIcon(item.name)">
              <component :is="getMenuIcon(item.name)" />
            </el-icon>
            <span>{{ item.name }}</span>
          </el-menu-item>
        </el-menu>
      </el-aside>
      <el-main class="layout-main">
        <div class="main-content">
          <router-view />
        </div>
      </el-main>
    </el-container>
    
    <!-- 个人信息弹窗 -->
    <el-dialog
      v-model="profileDialogVisible"
      title="个人信息"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="profileFormRef"
        :model="profileForm"
        :rules="profileRules"
        label-width="100px"
      >
        <el-form-item label="用户ID">
          <el-input v-model="profileForm.id" disabled />
        </el-form-item>
        <el-form-item label="用户名" prop="username">
          <el-input v-model="profileForm.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="姓名">
          <el-input v-model="profileForm.name" disabled />
        </el-form-item>
        <el-form-item label="角色">
          <el-input v-model="profileForm.role" disabled />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="profileForm.status" placeholder="请选择状态" style="width: 100%">
            <el-option label="正常" value="ACTIVE" />
            <el-option label="禁用" value="INACTIVE" />
          </el-select>
        </el-form-item>
        <el-form-item label="新密码" prop="password">
          <el-input
            v-model="profileForm.password"
            type="password"
            placeholder="留空则不修改密码"
            show-password
          />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
            v-model="profileForm.confirmPassword"
            type="password"
            placeholder="请再次输入密码"
            show-password
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="profileDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleUpdateProfile" :loading="updateLoading">
            保存
          </el-button>
        </span>
      </template>
    </el-dialog>
  </el-container>
</template>

<script>
import { ref, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import request from '../utils/request'
import { ElMessage } from 'element-plus'
import { 
  ArrowDown, 
  User, 
  SwitchButton,
  Clock,
  Document,
  Money,
  UserFilled,
  Setting,
  Timer,
  Check,
  View,
  DataAnalysis,
  Bell,
  Warning,
  Calendar
} from '@element-plus/icons-vue'

export default {
  name: 'Layout',
  components: {
    ArrowDown,
    User,
    SwitchButton,
    Clock,
    Document,
    Money,
    UserFilled,
    Setting,
    Timer,
    Check,
    View,
    DataAnalysis,
    Bell,
    Warning,
    Calendar
  },
  setup() {
    const router = useRouter()
    const route = useRoute()
    const menuList = ref([])
    const userInfo = ref({})
    const unreadCount = ref(0)
    const profileDialogVisible = ref(false)
    const profileFormRef = ref(null)
    const updateLoading = ref(false)
    const profileForm = ref({
      id: null,
      username: '',
      name: '',
      role: '',
      status: '',
      password: '',
      confirmPassword: ''
    })
    
    const activeMenu = computed(() => route.path)
    
    const userAvatar = computed(() => {
      return userInfo.value.avatar || ''
    })
    
    // 表单验证规则
    const validatePassword = (rule, value, callback) => {
      // 如果新密码为空，则不需要验证确认密码
      if (!profileForm.value.password) {
        callback()
        return
      }
      // 如果输入了新密码，则必须输入确认密码
      if (!value) {
        callback(new Error('请再次输入密码'))
      } else if (value !== profileForm.value.password) {
        callback(new Error('两次输入的密码不一致'))
      } else {
        callback()
      }
    }
    
    const profileRules = {
      username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' }
      ],
      password: [
        { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
      ],
      confirmPassword: [
        { validator: validatePassword, trigger: 'blur' }
      ]
    }
    
    const getRoleName = (role) => {
      const roleMap = {
        'EMPLOYEE': '员工',
        'MANAGER': '经理',
        'HR': 'HR',
        'OTHER': '其他'
      }
      return roleMap[role] || '用户'
    }
    
    const getRoleDisplayName = (role) => {
      const roleMap = {
        'EMPLOYEE': '员工',
        'MANAGER': '经理',
        'HR': 'HR',
        'OTHER': '其他'
      }
      return roleMap[role] || role
    }
    
    const getMenuIcon = (name) => {
      const iconMap = {
        '打卡签到': 'Clock',
        '考勤打卡': 'Clock',
        '加班申请': 'Timer',
        '请假申请': 'Document',
        '调休申请': 'Timer',
        '薪资查询': 'Money',
        '薪资查看': 'Money',
        '我的薪资': 'Money',
        '审批中心': 'Check',
        '审批加班': 'Check',
        '审批请假': 'Check',
        '团队考勤': 'View',
        '下属考勤查看': 'View',
        '团队薪资': 'Money',
        '员工管理': 'UserFilled',
        '薪资管理': 'Money',
        '考勤统计': 'DataAnalysis',
        '考勤异常管理': 'Warning',
        '假期统计': 'DataAnalysis',
        '假期余额': 'Calendar',
        '假期余额管理': 'Calendar',
        '系统设置': 'Setting',
        '数据可视化': 'DataAnalysis'
      }
      return iconMap[name] || 'Document'
    }
    
    // 加载未读消息数量
    const loadUnreadCount = async () => {
      try {
        const res = await request.get('/notification/unread-count')
        if (res.code === 200 && res.data) {
          unreadCount.value = res.data.unreadCount || 0
        }
      } catch (error) {
        // 忽略错误，不影响主流程
        // 如果服务不可用（404或其他错误），将未读数量设为0
        unreadCount.value = 0
        // 静默处理，不显示错误信息，因为通知服务是可选的
      }
    }
    
    // 跳转到消息中心
    const goToNotification = () => {
      router.push('/notification')
    }
    
    onMounted(() => {
      const userInfoStr = localStorage.getItem('userInfo')
      if (userInfoStr) {
        userInfo.value = JSON.parse(userInfoStr)
      }
      loadMenu()
      loadUnreadCount()
      
      // 每30秒刷新未读数量
      setInterval(() => {
        loadUnreadCount()
      }, 30000)
    })
    
    const loadMenu = async () => {
      try {
        const res = await request.get('/user/menu')
        menuList.value = res.data.menu || []
      } catch (error) {
        ElMessage.error('加载菜单失败')
      }
    }
    
    // 加载用户详细信息
    const loadUserProfile = async () => {
      try {
        const res = await request.get('/user/profile')
        if (res.code === 200 && res.data) {
          profileForm.value = {
            id: res.data.id,
            username: res.data.username || '',
            name: res.data.name || '',
            role: getRoleDisplayName(res.data.role) || '',
            status: res.data.status || 'ACTIVE',
            password: '',
            confirmPassword: ''
          }
        }
      } catch (error) {
        ElMessage.error('加载用户信息失败')
      }
    }
    
    // 更新用户信息
    const handleUpdateProfile = async () => {
      if (!profileFormRef.value) return
      
      try {
        await profileFormRef.value.validate()
        updateLoading.value = true
        
        const updateData = {
          username: profileForm.value.username,
          status: profileForm.value.status
        }
        
        // 如果输入了新密码，则更新密码
        if (profileForm.value.password) {
          updateData.password = profileForm.value.password
        }
        
        const res = await request.put('/user/profile', updateData)
        
        if (res.code === 200) {
          ElMessage.success('更新成功')
          profileDialogVisible.value = false
          
          // 更新本地存储的用户信息
          const userInfoStr = localStorage.getItem('userInfo')
          if (userInfoStr) {
            const localUserInfo = JSON.parse(userInfoStr)
            localUserInfo.username = profileForm.value.username
            localStorage.setItem('userInfo', JSON.stringify(localUserInfo))
            userInfo.value = localUserInfo
          }
        } else {
          ElMessage.error(res.message || '更新失败')
        }
      } catch (error) {
        if (error.response && error.response.data && error.response.data.message) {
          ElMessage.error(error.response.data.message)
        } else {
          ElMessage.error('更新失败')
        }
      } finally {
        updateLoading.value = false
      }
    }
    
    const handleCommand = (command) => {
      if (command === 'logout') {
        handleLogout()
      } else if (command === 'profile') {
        profileDialogVisible.value = true
        loadUserProfile()
      }
    }
    
    const handleLogout = () => {
      localStorage.removeItem('token')
      localStorage.removeItem('userInfo')
      ElMessage.success('已退出登录')
      router.push('/login')
    }
    
    return {
      menuList,
      userInfo,
      userAvatar,
      activeMenu,
      profileDialogVisible,
      profileForm,
      profileFormRef,
      profileRules,
      updateLoading,
      getRoleName,
      getMenuIcon,
      handleCommand,
      handleLogout,
      handleUpdateProfile,
      unreadCount,
      goToNotification
    }
  }
}
</script>

<style scoped>
.layout-container {
  width: 100%;
  height: 100vh;
  overflow: hidden;
}

.layout-header {
  height: 64px !important;
  background: #409eff;
  color: #fff;
  padding: 0 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  z-index: 1000;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 100%;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 16px;
}

.logo {
  display: flex;
  align-items: center;
}

.header-title {
  font-size: 20px;
  font-weight: 600;
  margin: 0;
  color: #fff;
  letter-spacing: -0.3px;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 16px;
}

.notification-badge {
  margin-right: 8px;
}

.notification-btn {
  border: none;
  background: rgba(255, 255, 255, 0.2);
  color: #fff;
  transition: all 0.3s;
}

.notification-btn:hover {
  background: rgba(255, 255, 255, 0.3);
}

.user-dropdown {
  display: flex;
  align-items: center;
  gap: 12px;
  cursor: pointer;
  padding: 8px 12px;
  border-radius: 8px;
  transition: background-color 0.3s;
}

.user-dropdown:hover {
  background-color: rgba(255, 255, 255, 0.1);
}

.user-info-text {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

.user-name {
  font-size: 14px;
  font-weight: 500;
  color: #fff;
  line-height: 1.4;
}

.user-role {
  font-size: 12px;
  color: rgba(255, 255, 255, 0.8);
  line-height: 1.4;
}

.dropdown-icon {
  color: rgba(255, 255, 255, 0.8);
  transition: transform 0.3s;
}

.layout-body {
  height: calc(100vh - 64px);
  overflow: hidden;
}

.layout-aside {
  background-color: #001529;
  border-right: 1px solid #e8e8e8;
  overflow-y: auto;
  overflow-x: hidden;
}

.sidebar-menu {
  border-right: none;
  background-color: #001529;
  height: 100%;
}

.sidebar-menu :deep(.el-menu-item) {
  color: rgba(255, 255, 255, 0.65);
  height: 56px;
  line-height: 56px;
  margin: 4px 8px;
  border-radius: 8px;
  transition: all 0.3s;
}

.sidebar-menu :deep(.el-menu-item:hover) {
  background-color: rgba(255, 255, 255, 0.08);
  color: #fff;
}

.sidebar-menu :deep(.el-menu-item.is-active) {
  background: #409eff;
  color: #fff;
  font-weight: 500;
}

.sidebar-menu :deep(.el-menu-item .el-icon) {
  margin-right: 12px;
  font-size: 18px;
}

.layout-main {
  background-color: #f0f2f5;
  padding: 24px;
  overflow-y: auto;
  height: 100%;
}

.main-content {
  width: 100%;
  height: 100%;
  max-width: 1400px;
  margin: 0 auto;
}

/* 滚动条样式 */
.layout-aside::-webkit-scrollbar,
.layout-main::-webkit-scrollbar {
  width: 6px;
  height: 6px;
}

.layout-aside::-webkit-scrollbar-track,
.layout-main::-webkit-scrollbar-track {
  background: transparent;
}

.layout-aside::-webkit-scrollbar-thumb {
  background: rgba(255, 255, 255, 0.2);
  border-radius: 3px;
}

.layout-main::-webkit-scrollbar-thumb {
  background: rgba(0, 0, 0, 0.2);
  border-radius: 3px;
}

.layout-aside::-webkit-scrollbar-thumb:hover,
.layout-main::-webkit-scrollbar-thumb:hover {
  background: rgba(0, 0, 0, 0.3);
}
</style>

